package cn.pegasus.teamwork.sysconfig.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;

import cn.iyizhan.teamwork.base.service.impl.BaseServiceImpl;
import cn.iyizhan.teamwork.base.util.PageHelper;
import cn.iyizhan.teamwork.base.util.PageObject;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigSms;
import cn.pegasus.teamwork.sysconfig.mapper.SysConfigSmsMapper;
import cn.pegasus.teamwork.sysconfig.service.SysConfigSmsService;
import cn.pegasus.teamwork.util.SmsUtils;
import cn.pegasus.teamwork.util.VerifyCodeUtils;

/**
 * @author buyuer
 * @version
 */
@Service
public class SysConfigSmsServiceImpl extends BaseServiceImpl<SysConfigSms, SysConfigSmsMapper> implements SysConfigSmsService {

    // 注入当前dao对象
    @Autowired
    private SysConfigSmsMapper sysConfigSmsMapper;
    
    public SysConfigSmsServiceImpl() {
        setMapperClass(SysConfigSmsMapper.class, SysConfigSms.class);
    }

    /*
     * (非 Javadoc) <p>Title: createCode</p> <p>Description: </p>
     * 
     * @param phone
     * 
     * @param userId
     * 
     * @param type
     * 
     * @see cn.iyizhan.teamwork.sysconfig.service.SysConfigSmsService#createCode(java.lang.String, int, int)
     */
    public int createCode(Long phone, Long userId, int type) {
    	// 查询数据库看看是否还存正正常的验证码
    	
    	HashMap<String, Object> map  =new HashMap<String,Object>();
    	SysConfigSms s = new SysConfigSms();
    	if(userId > 0){
    		s.setUserId(userId);
    		map.put("userId", userId);    		
    	}
    	map.put("phoneNumber", phone);
    	map.put("isVerification", 0);
    	map.put("smsType", type);
    	
    	s.setPhoneNumber(phone);
    	s.setIsVerification(0);
    	s.setSmsType(type);
    	
    	List<SysConfigSms> smses = sysConfigSmsMapper.selectByObject(s);
        if (smses != null && smses.size() >0) {        	
        	int count = 0 ;
        	for(SysConfigSms sss : smses){
        		// 创建时间 
				long t = sss.getCreateTime().getTime();
        		long vt = Long.valueOf(sss.getSmsEffectiveTime().toString());
        		if(new Date().getTime() > (t+vt)){
        			// 数据已经过期，进行数据库修改
        			sss.setIsVerification(2);
        			sysConfigSmsMapper.updateByEntity(sss);
        		}else {
        			count =count + 1;
        		}
        	}        	
        	if(count > 0){
        		return 2;
        	}
        }        
       
		try {
			String code = VerifyCodeUtils.generateVerifyCode(6);
			 boolean rs = SmsUtils.sendSms(phone.toString(), code);
			 if (rs) {
		        	SysConfigSms configSms = new SysConfigSms();
		        	int smsEffectiveTime = 10*60;
		            // 将短信验证码存入数据库
		        	if(userId > 0){
		        		configSms.setUserId(userId);		
		        	}
		            configSms.setSmsCode(code);
		            configSms.setSmsVercode(code);
		            configSms.setSmsType(type);
		            configSms.setIsVerification(0);
		            configSms.setSmsEffectiveTime(smsEffectiveTime);
		            configSms.setCreateTime(new Date());
		            configSms.setPhoneNumber(phone);
		            sysConfigSmsMapper.insertByEntity(configSms);
		            
		            return 0;
		        } else {
		            return 1;
		        }

		} catch (ClientException e) {
			e.printStackTrace();
		}        
       return 1;
    }

    /**
     * 手机验证码查询
     * @param phone
     * @param userId
     * @param type
     * @param code
     * @return
     */
    public boolean checkSms(Long phone, Long userId, int type, String code){
        SysConfigSms sms = new SysConfigSms();
//        if(userId > 0){
//        	sms.setUserId(userId);        	
//        }
        sms.setSmsType(type);
        sms.setPhoneNumber(phone);
        sms.setSmsCode(code);
        sms.setIsVerification(0);
        sms = sysConfigSmsMapper.selectSingle(sms);
        if (sms != null) {
            Long curr_time = System.currentTimeMillis();
            Long sms_time = sms.getCreateTime().getTime();
            int  timeNum = sms.getSmsEffectiveTime();
            sms.setIsVerification(2);
            sysConfigSmsMapper.updateByEntity(sms);
             if (curr_time > (sms_time + timeNum*1000)) {
                return false;
            }else{
                return true;
            }
        }
        return false;
    }
    
	@Override
	public PageObject<SysConfigSms> getPageSysConfigSms(Map<String, Object> map)
			throws Exception {
		SysConfigSms sysConfigSms = M2O(map);
		int totalData = sysConfigSmsMapper.getCount(sysConfigSms);
		PageHelper pageHelper = new PageHelper(totalData, map);
		List<SysConfigSms> list = sysConfigSmsMapper.pageQueryByObject(pageHelper.getMap());
		PageObject<SysConfigSms> pageObject = pageHelper.getPageObject();
		pageObject.setDataList(list);
		return pageObject;
	}

	@Override
	public boolean sendSerNotice(String phoneNumber, String carCode) {
		 try {
			boolean rs = SmsUtils.sendSerNotice(phoneNumber, carCode);
			return rs;
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean sendOrdNotice(String phoneNumber, String name, String orderCode, String orderTime) {
		try {
			boolean rs = SmsUtils.sendOrdNotice(phoneNumber, name, orderCode, orderTime);
			return rs;
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean refundsOrdNotice(String phoneNumber, String name, String orderCode, String orderTime) {
		try {
			boolean rs = SmsUtils.refundsOrdNotice(phoneNumber, name, orderCode, orderTime);
			return rs;
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean sendBeginServiceNotice(String phoneNumber, String name, String orderCode, String orderTime) {
		try {
			boolean rs = SmsUtils.sendBeginServiceNotice(phoneNumber, name,orderCode,orderTime);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean sendWasherRegYJSHNotice(String phoneNumber) {
		try {
			boolean rs = SmsUtils.sendWasherRegYJSHNotice(phoneNumber);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean sendWasherRegSHNotice(String phoneNumber,int type) {
		try {
			// 审核通过
			if(type ==1 ){
				boolean rs = SmsUtils.sendWasherRegSHNotice(phoneNumber);
				return rs;					
			} 
			 // 审核不通过
			else if(type ==2 ){
				boolean rs = SmsUtils.sendWasherRegSHNotNotice(phoneNumber);
				return rs;				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean sendWasherRegNotice(String phoneNumber) {
		try {
			boolean rs = SmsUtils.sendWasherRegNotice(phoneNumber);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
    
}
